package com.aaa.sso.service;

import com.aaa.sso.fegin.MenuFegin;
import com.aaa.sso.fegin.UserFegin;
import com.aaa.entity.Menu;
import com.aaa.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class MyUserServer implements UserDetailsService {
    @Autowired
    private MenuFegin menuFegin;

    @Autowired
    private UserFegin userFegin;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userFegin.getByUsername(username);
        if (user == null) {
            throw new RuntimeException("账号不存在");
        }
        //查询该用户具有的权限
        List<Menu> menuList = menuFegin.findByUserid(user.getUserId());
        List<SimpleGrantedAuthority> collect = menuList.stream().map(item -> new SimpleGrantedAuthority(item.getPercode())).collect(Collectors.toList());
        return new org.springframework.security.core.userdetails.User(user.getPhone(),user.getPassword(),collect);

    }
}
